package com.shangyueshang.controller;

import com.shangyueshang.response.HttpResult;
import com.shangyueshang.utils.QiNiuCloudUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author: JokeyZheng
 * @email: zhengjingfeng@ruqimobility.com
 * @created: 2022/1/26 14:50
 * @version: v1.0.0
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private QiNiuCloudUtil qiniuCloudUtil;

    /**
     * 上传文件
     *
     * @param file
     * @param module
     * @return
     */
    @PostMapping("/upload")
    public HttpResult upload(
            @RequestParam MultipartFile file,
            @RequestParam(required = false) String module
    ) {
        if (file.isEmpty()) {
            return HttpResult.fail("上传文件不能为空");
        }
        try {
            byte[] bytes = file.getBytes();
            try {
                //文件名
                //  String fileName = FileName.getFileName(file);
                //使用base64方式上传到七牛云
                String key = StringUtils.hasText(module) ? module + "/" + file.getOriginalFilename() : file.getOriginalFilename();
                return qiniuCloudUtil.upload(bytes, key);
            } catch (Exception e) {
                e.printStackTrace();
                return HttpResult.fail("文件上传发生异常");
            }
        } catch (IOException e) {
            return HttpResult.fail("文件上传发生异常");
        }
    }

    /**
     * 删除文件
     *
     * @param fileUrl
     * @return
     * @throws Exception
     */
    @PostMapping("/delete")
    public HttpResult delete(@RequestParam(required = false) String fileUrl) throws Exception {
        if (!StringUtils.hasText(fileUrl)) {
            return HttpResult.ok();
        }
        return qiniuCloudUtil.delete(fileUrl);
    }
}
